<template>
  <div class="course-selection-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>课程选择</span>
          <el-button type="primary" @click="handleMyCourses">
            我的课程
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" class="search-form" label-width="80px">
        <el-form-item label="学院">
          <el-select
            v-model="queryForm.collegeId"
            placeholder="请选择学院"
            clearable
            filterable
            style="width: 200px"
            @change="handleQuery"
          >
            <el-option
              v-for="college in collegeOptions"
              :key="college.id"
              :label="college.name"
              :value="college.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入课程名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>
      
      <!-- 课程表格 -->
      <el-table
        v-loading="loading"
        :data="courseList"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="课程名称" min-width="200" />
        <el-table-column prop="courseCode" label="课程码" width="120" />
        <el-table-column label="所属学院" width="150">
          <template #default="{ row }">
            {{ getCollegeName(row.collegeId) }}
          </template>
        </el-table-column>
        <el-table-column label="主讲教师" width="120">
          <template #default="{ row }">
            {{ getTeacherName(row.teacherId) }}
          </template>
        </el-table-column>
        <el-table-column label="选课状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.selected ? 'success' : 'info'">
              {{ row.selected ? '已选' : '未选' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="!row.selected"
              type="primary"
              size="small"
              @click="handleSelect(row.id)"
            >
              选课
            </el-button>
            <el-button
              v-else
              type="danger"
              size="small"
              @click="handleUnselect(row.id)"
            >
              退课
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 我的课程对话框 -->
    <el-dialog
      v-model="myCoursesDialogVisible"
      title="我的课程"
      width="800px"
    >
      <el-table
        v-loading="myCoursesLoading"
        :data="myCoursesList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="课程名称" min-width="200" />
        <el-table-column prop="courseCode" label="课程码" width="120" />
        <el-table-column label="所属学院" width="150">
          <template #default="{ row }">
            {{ getCollegeName(row.collegeId) }}
          </template>
        </el-table-column>
        <el-table-column label="主讲教师" width="120">
          <template #default="{ row }">
            {{ getTeacherName(row.teacherId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              @click="handleUnselect(row.id)"
            >
              退课
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getCourseList } from '../../api/course'
import { getAllColleges } from '../../api/college'
import { getUserList } from '../../api/user'
import { selectCourse, unselectCourse, checkCourseSelected, getMySelectedCourses } from '../../api/course'

// 定义接口类型
interface College {
  id: number;
  name: string;
}

interface Teacher {
  id: number;
  realName: string;
}

interface Course {
  id: number;
  name: string;
  courseCode: string;
  collegeId?: number;
  teacherId?: number;
  selected?: boolean;
}

const loading = ref(false)
const myCoursesLoading = ref(false)
const courseList = ref<Course[]>([])
const myCoursesList = ref<Course[]>([])
const collegeOptions = ref<College[]>([])
const teacherOptions = ref<Teacher[]>([])
const myCoursesDialogVisible = ref(false)

const queryForm = reactive({
  name: '',
  collegeId: null
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 获取学院名称
const getCollegeName = (collegeId: number) => {
  const college = collegeOptions.value.find((c: any) => c.id === collegeId)
  return college ? college.name : '-'
}

// 获取教师名称
const getTeacherName = (teacherId: number) => {
  const teacher = teacherOptions.value.find((t: any) => t.id === teacherId)
  return teacher ? teacher.realName : '-'
}

// 加载学院列表
const loadColleges = async () => {
  try {
    const res = await getAllColleges()
    collegeOptions.value = res.data || []
  } catch (error) {
    ElMessage.error('获取学院列表失败')
  }
}

// 加载教师列表
const loadTeachers = async () => {
  try {
    const res = await getUserList({
      roleType: 'TEACHER',
      page: 1,
      size: 1000
    })
    teacherOptions.value = res.data.data || []
  } catch (error) {
    ElMessage.error('获取教师列表失败')
  }
}

// 检查课程选课状态
const checkCourseStatus = async () => {
  for (const course of courseList.value) {
    try {
      const res = await checkCourseSelected(course.id)
      course.selected = res.data
    } catch (error) {
      course.selected = false
    }
  }
}

// 获取课程列表
const fetchCourseList = async () => {
  loading.value = true
  try {
    const queryParams: any = {
      name: queryForm.name || undefined,
      collegeId: queryForm.collegeId || undefined,
      page: pagination.page,
      size: pagination.size
    }
    
    const res = await getCourseList(queryParams)
    
    // res 就是 ApiResponse，res.data 是 PageResult，res.data.data 是列表数据
    courseList.value = res.data.data || []
    pagination.total = res.data.total || 0
    
    // 检查每个课程的选课状态
    await checkCourseStatus()
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  fetchCourseList()
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  queryForm.collegeId = null
  handleQuery()
}

// 分页改变
const handlePageChange = (page: number) => {
  pagination.page = page
  fetchCourseList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchCourseList()
}

// 选课
const handleSelect = async (courseId: number) => {
  try {
    await selectCourse(courseId)
    ElMessage.success('选课成功')
    // 更新当前课程的选课状态
    const course = courseList.value.find((c: any) => c.id === courseId)
    if (course) {
      course.selected = true
    }
  } catch (error) {
    // 错误已在拦截器中处理
  }
}

// 退课
const handleUnselect = async (courseId: number) => {
  try {
    await unselectCourse(courseId)
    ElMessage.success('退课成功')
    // 更新当前课程的选课状态
    const course = courseList.value.find((c: any) => c.id === courseId)
    if (course) {
      course.selected = false
    }
    // 如果是在我的课程对话框中，刷新列表
    if (myCoursesDialogVisible.value) {
      await loadMyCourses()
    }
  } catch (error) {
    // 错误已在拦截器中处理
  }
}

// 查看我的课程
const handleMyCourses = async () => {
  myCoursesDialogVisible.value = true
  await loadMyCourses()
}

// 加载我的课程
const loadMyCourses = async () => {
  myCoursesLoading.value = true
  try {
    const res = await getMySelectedCourses()
    myCoursesList.value = res.data || []
  } catch (error) {
    ElMessage.error('获取我的课程失败')
  } finally {
    myCoursesLoading.value = false
  }
}

onMounted(async () => {
  await loadColleges()
  await loadTeachers()
  fetchCourseList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>



